package com.hmdp.controller;


import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;
import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 */
@Slf4j
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        //创建TypeList
        List<ShopType> typeList = new ArrayList<>();
        //1.先从缓存里面查找
        Long size = stringRedisTemplate.opsForList().size(SHOP_TYPE_KEY);
        log.info("size:{}",size);
        if (size!=0){
            for (Long i = Long.valueOf(0); i < size; i++) {
                //1.1.查到数据存入typeList中
                typeList.add(JSONUtil.toBean(stringRedisTemplate.opsForList().index(SHOP_TYPE_KEY,i),ShopType.class));
            }
            //1.2.返回数据
            return Result.ok(typeList);
        }
        //到这里说明Redis中还没有数据
        //2.查数据库
        typeList = typeService.query().orderByAsc("sort").list();
        //3.typeList已经包含了数据
        typeList = typeList.stream().map(
                (item) -> {
                    //3.1.数据格式不符合redis存储，需要转化
                    stringRedisTemplate.opsForList().rightPush(SHOP_TYPE_KEY,JSONUtil.toJsonStr(item));
                    log.info("saving---------------------->{}", item);
                    return item;
                }
        ).collect(Collectors.toList());
        //4.刷新缓存存储时间
        stringRedisTemplate.expire(SHOP_TYPE_KEY,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(typeList);

    }
}
